<template>
  <div style="width: 100%; height: 100%; position: relative">
    <div style="width: 100%; height: 100%" id="map"></div>
    <div
      style="position: absolute; top: 0px; right: 0px; z-index: 999; padding: 5px"
    ></div>
    <div style="position: absolute; top: 0px; right: 0px; z-index: 999; padding: 5px">
      <el-button @click="distance">距离量算</el-button>
      <el-button @click="area">面积量算</el-button>
      <el-button @click="startDrawBox">空间查询</el-button>
      <el-button @click="circleBuffer">缓冲区查询</el-button>

    </div>
    <el-dialog
      title="查询结果"
      v-model="resultDialogVisible"
    >
      <el-table :data="resultTableData" style="width: 100%">
        <el-table-column prop="名称" label="学校名称"></el-table-column>
        <el-table-column prop="学校标识码" label="学校标识码"></el-table-column>
        <el-table-column prop="主管部门" label="主管部门"></el-table-column>
        <el-table-column prop="所在地" label="所在地"></el-table-column>
        <el-table-column prop="办学层次" label="办学层次"></el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import http from "../utils/http";
import { ElMessage, ElMessageBox } from "element-plus";
let map = null;
let selecti, source, drawsource, popup;
const tableData = ref([]);
const resultTableData = ref([]);
const resultDialogVisible = ref(false);
const getPavilions = async () => {
  const res = await http.get("/allstation");
  console.log(res);

  tableData.value = res.data;
 //在地图上绘制点
  source.clear();
  for (let i = 0; i < res.data.length; i++) {
    //转换为3857
    let point_3857 = new ol.geom.Point([res.data[i].x, res.data[i].y]).transform(
      "EPSG:4326",
      "EPSG:3857"
    );
    let feature = new ol.Feature({
      geometry: point_3857,
      名称: res.data[i].name,
      学校标识码: res.data[i].code,
      主管部门: res.data[i].department,
      所在地: res.data[i].address,
      办学层次: res.data[i].level,
      x: res.data[i].x,
      y: res.data[i].y,
    });
    source.addFeature(feature);
  }
  //fit
  if (res.data.length > 0) {
    var extent = source.getExtent();
    map.getView().fit(extent, map.getSize());
  }
};
const distance = () => {
  var drawLine = new ol.interaction.Draw({ type: "LineString" });
  map.addInteraction(drawLine);

  // Add a tooltip
  var tooltip = new ol.Overlay.Tooltip();
  map.addOverlay(tooltip);

  // Set feature on drawstart
  drawLine.on("drawstart", tooltip.setFeature.bind(tooltip));
  // Remove feature on finish 并且移除drawLine
  drawLine.on(["change:active", "drawend"], function (e) {
    tooltip.removeFeature(e);
    map.removeInteraction(drawLine);
  });
};

const area = () => {
  var drawPolygon = new ol.interaction.Draw({ type: "Polygon" });
  map.addInteraction(drawPolygon);

  // Add a tooltip
  var tooltip = new ol.Overlay.Tooltip();
  map.addOverlay(tooltip);

  // Set feature on drawstart
  drawPolygon.on("drawstart", tooltip.setFeature.bind(tooltip));
  // Remove feature on finish 并且移除drawPolygon
  drawPolygon.on(["change:active", "drawend"], function (e) {
    tooltip.removeFeature(e);
    map.removeInteraction(drawPolygon);
  });
};
const startDrawBox = () => {
  //矩形框选
  var drawBox = new ol.interaction.Draw({
    type: "Circle",
    geometryFunction: ol.interaction.Draw.createBox(),
  });
  map.addInteraction(drawBox);
  //结束绘制
  drawBox.on("drawend", function (e) {
    var extent = e.feature.getGeometry().getExtent();
    //获取框选范围内的点
    var features = source.getFeaturesInExtent(extent);
    console.log(features);
    resultTableData.value = features.map((item) => item.values_);
    resultDialogVisible.value = true;
    map.removeInteraction(drawBox);
 

    //fit
    if (features.length > 0) {
      var extent = ol.extent.createEmpty();
      features.forEach(function (feature) {
        ol.extent.extend(extent, feature.getGeometry().getExtent());
      });
      map.getView().fit(extent, map.getSize());
    }
  });


};
const circleBuffer = ()=>{
  var drawCircle = new ol.interaction.Draw({
    type: "Point",
  });
  map.addInteraction(drawCircle);
  //结束绘制
  drawCircle.on("drawend", function (e) {
    //输入半径
    ElMessageBox.prompt("请输入半径", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /^\d+$/,
      inputErrorMessage: "请输入数字",
    }).then(({ value }) => {
      var center = e.feature.getGeometry().getFirstCoordinate();
      var value = parseInt(value);
      var circle = new ol.geom.Circle(center, value*1000);

      //获取圆形范围内的点
      var features = source.getFeaturesInExtent(circle.getExtent());
      console.log(features);
      resultTableData.value = features.map((item) => item.values_);
      resultDialogVisible.value = true;

      map.removeInteraction(drawCircle);
      //在地图上绘制圆
      drawsource.clear();
      var circleFeature = new ol.Feature({
        geometry: circle,
      });
      drawsource.addFeature(circleFeature);

      //fit
      if (features.length > 0) {
        var extent = ol.extent.createEmpty();
        features.forEach(function (feature) {
          ol.extent.extend(extent, feature.getGeometry().getExtent());
        });
        map.getView().fit(extent, map.getSize());
      }
    });
  });

}
onMounted(() => {
  var dataLayer = new ol.layer.Vector({
    title: "高校数据",
    //红色的点
    style: new ol.style.Style({
      image: new ol.style.Circle({
        radius: 5,
        fill: new ol.style.Fill({
          color: "red",
        }),
      }),
    }),
    source: (source = new ol.source.Vector()),
  });
  var drawLayer = new ol.layer.Vector({
    title: "缓冲区",
    source: (drawsource = new ol.source.Vector()),
  });
  var heatmap = new ol.layer.Heatmap({
    title: "高校热力图",
    source: dataLayer.getSource(),
    blur: 15,
    radius: 5,
    visible: false,
  });
  map = new ol.Map({
    target: "map",
    layers: [
      new ol.layer.Tile({
        title: "高德地图",
        //高德地图
        source: new ol.source.XYZ({
          url: "https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
        }),
      }),
      //高德地图标注
      new ol.layer.Tile({
        title: "高德地图标注",
        source: new ol.source.XYZ({
          url: "https://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}",
        }),
      }),
      dataLayer,
      heatmap,
      drawLayer,
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([118.316, 32.301]),
      zoom: 13,
      maxZoom: 18,
    }),
  });
  getPavilions();
  map.addControl(new ol.control.LayerPopup());
  // Select  interaction
  selecti = new ol.interaction.Select({
    hitTolerance: 5,
    condition: ol.events.condition.singleClick,
    layers: [dataLayer],
  });
  map.addInteraction(selecti);

  // Select control
  popup = new ol.Overlay.PopupFeature({
    popupClass: "default anim",
    select: selecti,
    canFix: true,
  });
  map.addOverlay(popup);
  // Select feature when click on the reference index
  selecti.on("select", function (e) {
    var f = e.selected[0];
    if (f) {
      listCtrl.select(f);
    }
  });

  // Select control
  var listCtrl = new ol.control.FeatureList({
    title: "高校",
    // className: 'ol-bottom',
    collapsed: true,
    features: source,
    // target: document.body
  });
  listCtrl.enableSort("nom", "region");
  map.addControl(listCtrl);
  listCtrl.on("select", function (e) {
    selecti.getFeatures().clear();
    selecti.getFeatures().push(e.feature);
    //show(coordinate, features, current)
    popup.show(e.coordinate, e.feature);
  });
  listCtrl.on("dblclick", function (e) {
    map.getView().fit(e.feature.getGeometry().getExtent());
    map.getView().setZoom(map.getView().getZoom() - 1);
  });

  listCtrl.on(["resize", "collapse"], function (e) {
    console.log(e);
  });
  // Set the control grid reference
  var search = new ol.control.SearchFeature({
    //target: $(".options").get(0),
    source: source,
    property: "名称",
    sort: function (f1, f2) {
      if (search.getSearchString(f1) < search.getSearchString(f2)) return -1;
      if (search.getSearchString(f1) > search.getSearchString(f2)) return 1;
      return 0;
    },
  });
  map.addControl(search);

  // selecti feature when click on the reference index
  search.on("select", function (e) {
    console.log(e);
    selecti.getFeatures().clear();
    selecti.getFeatures().push(e.search);
    listCtrl.select(e.search);
    var p = e.search.getGeometry().getFirstCoordinate();
    popup.show(p, e.search);
    map.getView().animate({ center: p });
  });
  document.getElementsByClassName("search")[0].placeholder = "请输入名称";
});
</script>
</script>